import { useMemo } from 'react'
import { Button, FormInstance, Popconfirm, Tooltip } from 'antd'
import { DeleteOutlined } from '@ant-design/icons'

import { CusAgGrid } from '@/components/CusAgGrid'
import { dhFormat } from '@/utils/utils'
import { Cell } from './components'
import { IChannelListItem, TCellParams, TCol, TFormValues } from './interface'
import { useCommonCols } from './useCommonCols'

const ActionCell = (p: TCellParams<'channelId'> & { form: FormInstance<TFormValues> }) => {
  const { value } = p as TCellParams<'channelId'>
  if (value == null) return
  return (
    <Tooltip title="删除">
      <Popconfirm
        title="确认要删除吗？"
        onConfirm={() => {
          let list: TFormValues['routeChannelList'] = p.form.getFieldValue('routeChannelList')
          list = list.filter(d => d.channelId !== value)
          p.form.setFieldValue('routeChannelList', list)
        }}
      >
        <Button type="link" danger icon={<DeleteOutlined />} />
      </Popconfirm>
    </Tooltip>
  )
}

export const Channels = ({ data, form }: { data: IChannelListItem[]; form: FormInstance<TFormValues> }) => {
  const commonCols = useCommonCols()

  // 列配置
  const defaultColDef = useMemo<Partial<TCol>>(
    () => ({
      flex: 1,
      minWidth: 121,
      sortable: false,
      cellRenderer: Cell,
    }),
    [],
  )
  const columnDefs = useMemo(
    () => [
      ...commonCols,
      {
        field: 'keepDate',
        headerName: '持续时间',
        flex: 0.01,
        minWidth: 114,
        valueFormatter: ({ value }) => dhFormat(value),
      } satisfies TCol<'keepDate'>,
      {
        field: 'channelId',
        headerName: '操作',
        flex: 0.01,
        width: 86,
        minWidth: 86,
        pinned: 'right',
        cellRenderer: ActionCell,
        cellRendererParams: { form },
      } satisfies TCol<'channelId'>,
    ],
    [commonCols, form],
  )

  return (
    <div style={{ height: 253 }}>
      <CusAgGrid<IChannelListItem> rowData={data} defaultColDef={defaultColDef} columnDefs={columnDefs} />
    </div>
  )
}
